package com.demo.common.tool;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.imageio.ImageIO;

public class ToolPicture {

	public static void saveToFile(String destUrl, String picPath, String type) {
		HttpURLConnection httpUrl = null;
		URL url = null;
		BufferedImage bufferedImage = null;
		BufferedImage newBufferedImage = null;
		try {
			url = new URL(destUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.connect();

			bufferedImage = ImageIO.read(httpUrl.getInputStream());
			newBufferedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);
			newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
			ImageIO.write(newBufferedImage, type, new File(picPath));
			bufferedImage.flush();
			newBufferedImage.flush();
		} catch (IOException e) {
		} catch (ClassCastException e) {
		} finally {
			try {
				httpUrl.disconnect();
			} catch (NullPointerException e) {
			}
		}
	}

	public static void saveToFile(String destUrl, String picPath) {
		FileOutputStream fos = null;
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		URL url = null;
		int BUFFER_SIZE = 1024;
		byte[] buf = new byte[BUFFER_SIZE];
		int size = 0;
		try {
			url = new URL(destUrl);
			httpUrl = (HttpURLConnection) url.openConnection();
			httpUrl.connect();

			bis = new BufferedInputStream(httpUrl.getInputStream());
			fos = new FileOutputStream(picPath);

			while ((size = bis.read(buf)) != -1) {
				fos.write(buf, 0, size);
			}
			fos.flush();
		} catch (IOException e) {
		} catch (ClassCastException e) {
		} finally {
			try {
				fos.close();
				bis.close();
				httpUrl.disconnect();
			} catch (IOException e) {
			} catch (NullPointerException e) {
			}
		}
	}

	public static String changeType(String picPath, String type) throws Exception {
		String _picPath = picPath.substring(0, picPath.indexOf(".") + 1) + type;
		BufferedImage bufferedImage;
		bufferedImage = ImageIO.read(new File(picPath));
		BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(),
				BufferedImage.TYPE_INT_RGB);
		newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);
		ImageIO.write(newBufferedImage, type, new File(_picPath));
		return _picPath;
	}
}
